package com.ymatou.iapi.im.testcase;

import com.google.gson.JsonObject;
import com.ymatou.iapi.im.parameter.SendMessageToBuyerBean;
import com.ymatou.iapi.im.service.SendMessageToBuyerCall;
import com.ymatou.iapi.userregister.parameter.UserRegisterInfoRequestDtoBean;
import com.ymatou.iapi.userregister.service.UserRegisterInfoRequestDtoCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P2;
import com.ymttest.business.service.AssertService;
import com.ymttest.business.service.ImCallService;
import com.ymttest.business.service.JUserCallService;
import com.ymttest.database.model.YmtMessage;
import com.ymttest.database.redis.ImRedisWapper;
import com.ymttest.database.sqlwapper.ImDefaultWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;
import org.junit.*;
import org.junit.experimental.categories.Category;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class Ts_SendMessageToBuyer {
	public static SendMessageToBuyerCall sendcall;
    public static SendMessageToBuyerBean sendbean;
    //普通买手
    private static int sellerId = Integer.parseInt(EnvSetup.getData("autotest_seller1"));
    //101买家
    private static int globalSellerId = Integer.parseInt(EnvSetup.getData("globalSellerId"));
	private static ImRedisWapper redis=new ImRedisWapper();
    @BeforeClass
	public static void setUp() {
		Logger.createResultFile("IM java接口");
	}

	@Before
	public void caseUp() {
		sendcall = new SendMessageToBuyerCall();
		sendbean = new SendMessageToBuyerBean();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(sendcall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	public static void verifyDB(SendMessageToBuyerBean sendbean) throws InterruptedException, IOException, ParseException {
        JsonObject ret = sendcall.getJsonObject().get("Result").getAsJsonObject();
        String messageId = ret.get("messageId").getAsString();
        //验证Message
        YmtMessage ymtMessage = new ImDefaultWapper().selectImInfo(messageId).get(0);
        Logger.verifyEquals(sendbean.getFromUserId(),ymtMessage.getMsgFromId(),"验证买手id");
        Logger.verifyEquals(sendbean.getToUserId(),ymtMessage.getMsgToId(),"验证买家id");
        Logger.verifyEquals(sendbean.getCSName(),ymtMessage.getMsgFrom(),"验证买手名称");
        Logger.verifyEquals(sendbean.getAppId(),ymtMessage.getAppId(),"验证买手名称");
        Logger.verifyEquals(ret.get("toUserName").getAsString(),JUserCallService.GetUserInfo(sendbean.getToUserId()).getLoginId(),"验证买家名称");
		Logger.verifyEquals(ret.get("fromUserLogo").getAsString(),JUserCallService.GetLogoUrl(sendbean.getFromUserId()),"验证买手logo");
		Logger.verifyEquals(ret.get("toUserLogo").getAsString(),JUserCallService.GetLogoUrl(sendbean.getToUserId()),"验证买家logo");
		String tgPostTime = ret.get("postTime").getAsString();
		DateFormat format = new SimpleDateFormat(YMTDateUtil.YMDTHMS_STRING);
		Date time = format.parse(tgPostTime);
		AssertService.assertTime(time,ymtMessage.getPostTime(),2,"验证PostTime");
		if(sendbean.getSessionNumber()==null){
            Logger.verifyEquals(ret.get("isCancel").getAsBoolean(),false,"验证iscancel");
        }else{
            Logger.verifyEquals(ret.get("isCancel").getAsBoolean(),ymtMessage.getIsCancel()==1?true:false,"验证iscancel");
        }
        if(ret.get("isCancel").getAsBoolean()==true){
            Logger.verifyEquals(1,ymtMessage.getHaveAttach(),"撤回消息含有附件");
            if(sendbean.getFromUserId()>sendbean.getToUserId()){
                Logger.verifyEquals(1,ymtMessage.getSmallSee(),"验证smallsee字段");
            }else{
                Logger.verifyEquals(1,ymtMessage.getBigSee(),"验证bigsee字段");
            }
            new ImDefaultWapper().selectMessageattachByMessageId(messageId).forEach(p->{
                Logger.verifyEquals(true,p.getContent().contains("为了买卖双方的交易安全和体验，请勿引导至站外平台。当前消息已屏蔽！"),"验证附件中包含此条消息");
            });
        }else{
            Logger.verifyEquals(0,ymtMessage.getHaveAttach(),"普通消息不含有附件");
        }
        //验证session  有两个session
        if(sendbean.getFromUserId() != globalSellerId){//101session单独另存
            Map mapSession = new ImDefaultWapper().selectTotalCount(sendbean.getFromUserId(),sendbean.getToUserId()).get(0);
            Logger.debug("mapSession:"+mapSession);
            Logger.verifyEquals(sendbean.getToUserId(), Integer.parseInt(mapSession.get("UserId").toString()),"验证session表中买家id");
            Logger.verifyEquals(sendbean.getFromUserId(),Integer.parseInt(mapSession.get("OtherUserId").toString()),"验证session表中买手id");

        }
        Map mapSession1 = new ImDefaultWapper().selectTotalCount(sendbean.getToUserId(),sendbean.getFromUserId()).get(0);
        Logger.debug("mapSession1:"+mapSession1);
        Logger.verifyEquals(sendbean.getToUserId(),Integer.parseInt(mapSession1.get("OtherUserId").toString()),"验证买家");
        Logger.verifyEquals(sendbean.getFromUserId(),Integer.parseInt(mapSession1.get("UserId").toString()),"验证买手");
    }

	/**
	 * 返回报文：
	 * fromUserUnReadMessageCount
	 * toUserUnReadMessageCount
	 * 字段已经废弃
	 */
	@Test
	@Category({P1.class})
	@TestCase
	public void Ts_SendMessageToBuyer_001(){
        Logger.start(true, "买手向买家发送一条消息，发送成功");
        try {
            //注册用户
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer userId = urrc.getUserid();
			//发送消息
            sendbean = ImCallService.initSendMessageToBuyerBean(sellerId,userId,"你好啊");
            sendcall.setData(sendbean);
            sendcall.callService();
            Logger.verifyEquals("Success",sendcall.getString("Status"),"验证status");
            verifyDB(sendbean);
			//计数服务
			int unRead = ImCallService.GetMessageCount(sendbean.getToUserId());
			Logger.verifyEquals(1,unRead,"验证买家有一条消息未读");
		}
		catch(Exception e ) {
			Logger.fail(e);
		}

	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Ts_SendMessageToBuyer_002(){
		Logger.start(true, "买手向买家发送图片，发送成功");
        try {
            //注册用户
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer userId = urrc.getUserid();
            //发送消息
            String message = "[img]http://pic1.ymatou.com/G01/M00/2F/5D/rBBlD1hg8JqAcw_pAAOQn3fB5wk437_8_5_o.jpg#274x171[/img]";
            sendbean = ImCallService.initSendMessageToBuyerBean(sellerId,userId,message);
            sendcall.setData(sendbean);
            sendcall.callService();
            Logger.verifyEquals("Success",sendcall.getString("Status"),"验证status");
            verifyDB(sendbean);
            //计数服务
            int unRead = ImCallService.GetMessageCount(sendbean.getToUserId());
            Logger.verifyEquals(1,unRead,"验证买家有一条消息未读");
		}
		catch(Exception e ) {
			Logger.fail(e);
		}
		
		
		
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Ts_SendMessageToBuyer_003(){
		Logger.start(true, "买家向买手发送表情，发送成功");
        try {
            //注册用户
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer userId = urrc.getUserid();
            //发送消息
            String message = "😁";
            sendbean = ImCallService.initSendMessageToBuyerBean(sellerId,userId,message);
            sendcall.setData(sendbean);
            sendcall.callService();
            Logger.verifyEquals("Success",sendcall.getString("Status"),"验证status");
            verifyDB(sendbean);
            //计数服务
            int unRead = ImCallService.GetMessageCount(sendbean.getToUserId());
            Logger.verifyEquals(1,unRead,"验证买家有一条消息未读");
		}
		catch(Exception e ) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Ts_SendMessageToBuyer_004(){
		Logger.start(true, "买手向买家发送特殊字符，发送成功");
		try {
            //注册用户
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer userId = urrc.getUserid();
            //发送消息
            String message = "！）（*&……@￥测试测试导出";
            sendbean = ImCallService.initSendMessageToBuyerBean(sellerId,userId,message);
            sendcall.setData(sendbean);
            sendcall.callService();
            Logger.verifyEquals("Success",sendcall.getString("Status"),"验证status");
            verifyDB(sendbean);
            //计数服务
            int unRead = ImCallService.GetMessageCount(sendbean.getToUserId());
            Logger.verifyEquals(1,unRead,"验证买家有一条消息未读");
		}
		catch(Exception e ) {
			Logger.fail(e);
		}
		
		
		
	}
	
	@Test
	@Category({P2.class})
	@TestCase
	public void Ts_SendMessageToBuyer_005(){
		Logger.start(true, "内容为空，发送失败");
		try {
            //注册用户
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer userId = urrc.getUserid();
            //发送消息
            String message = null;
            sendbean = ImCallService.initSendMessageToBuyerBean(sellerId,userId,message);
            sendcall.setData(sendbean);
            sendcall.callService();
            Logger.verifyEquals("ParameterError",sendcall.getString("Status"),"验证status");
            //计数服务
            int unRead = ImCallService.GetMessageCount(sendbean.getToUserId());
            Logger.verifyEquals(0,unRead,"验证买家未收到消息");
		}
		catch(Exception e ) {
			Logger.fail(e);
		}

	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Ts_SendMessageToBuyer_006(){
	    Logger.start(true,"101向买家发送消息");
		try {
            //注册用户
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer userId = urrc.getUserid();
            //发送消息
            String message = "nihao a";
            sendbean = ImCallService.initSendMessageToBuyerBean(globalSellerId,userId,message);
            sendcall.setData(sendbean);
            sendcall.callService();
            Logger.verifyEquals("Success",sendcall.getString("Status"),"验证status");
            verifyDB(sendbean);
            //计数服务
            int unRead = ImCallService.GetGlobalMessageCount(sendbean.getToUserId());
            //101买手隔离
            Logger.verifyEquals(1,unRead,"验证买家有一条消息未读");
		}
		catch(Exception e ) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P2.class})
	@TestCase
	public void Ts_SendMessageToBuyer_007(){
		Logger.start(true, "微信导流拦截 敏感词校验");
		try {
            //注册用户
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer userId = urrc.getUserid();
            //发送消息
            String message = "微信";
            sendbean = ImCallService.initSendMessageToBuyerBean(sellerId,userId,message);
            sendcall.setData(sendbean);
            sendcall.callService();
            Logger.verifyEquals("Success",sendcall.getString("Status"),"验证status");
            verifyDB(sendbean);
            //计数服务
            int unRead = ImCallService.GetMessageCount(sendbean.getToUserId());
            Logger.verifyEquals(1,unRead,"验证买家有一条消息未读");
		}
		catch(Exception e ) {
			Logger.fail(e);
		}

	}

    @Test
    @Category({P2.class})
    @TestCase
    public void Ts_SendMessageToBuyer_0010(){
        Logger.start(true, "微信导流拦截 二维码校验");
        try {
            //注册用户
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer userId = urrc.getUserid();
            //发送消息
            String message = "[img]http://pic1.ymatou.com/G01/M00/3F/08/rBBlD1xqfN2AIeinAACZjtTW7pU668_1_1_o.jpg#246x246[/img]";
            sendbean = ImCallService.initSendMessageToBuyerBean(sellerId,userId,message);
            sendcall.setData(sendbean);
            sendcall.callService();
            Logger.verifyEquals("Success",sendcall.getString("Status"),"验证status");
            verifyDB(sendbean);
            //计数服务
//            int unRead = ImCallService.GetMessageCount(sendbean.getToUserId());
//            Logger.verifyEquals(1,unRead,"验证买家有一条消息未读");
        }
        catch(Exception e ) {
            Logger.fail(e);
        }

    }

	@Test
	@Category({P2.class})
	@TestCase
    @Ignore
	public void Ts_SendMessageToBuyer_008(){
		Logger.start(true, "微信导流拦截 敏感词校验，买手可见，买家最后一条消息不可见,买手全部可见");
		try {
		    Logger.comment("在GetMessageListAndSessionByTimeline做了校验");
		}
		catch(Exception e ) {
			Logger.fail(e);
		}
	}

    @Test
    @Category({P2.class})
    @TestCase
    @Ignore
    public void Ts_SendMessageToBuyer_009(){
        Logger.start(true, "买手给买手发送消息,不做校验");
        try {
            int seller1 = 3383;
            SendMessageToBuyerBean sendMessage1 = ImCallService.initSendMessageToBuyerBean(sellerId,seller1,"你好");
            sendcall.setData(sendMessage1);
            sendcall.callService();
        }
        catch(Exception e ) {
            Logger.fail(e);
        }
    }

    @Test
    @Category({P2.class})
    @TestCase
    public void Ts_SendMessageToBuyer_010(){
        Logger.start(true, "买手给买家发送消息,不传sessionNumber,微信导流，iscancel为false");
        try {
            UserRegisterInfoRequestDtoBean regbean = JUserCallService.initUserRegisterInfoRequestDtoBean();
            UserRegisterInfoRequestDtoCall urrc = JUserCallService.UserRegisterInfoRequestDtoCall(regbean);
            Integer toUserId = urrc.getUserid();
            SendMessageToBuyerBean sendMessage = ImCallService.initSendMessageToBuyerBean(sellerId,toUserId,"微信");
            sendMessage.setSessionNumber(null);
            sendcall.setData(sendMessage);
            sendcall.callService();
            verifyDB(sendMessage);
        }
        catch(Exception e ) {
            Logger.fail(e);
        }
    }

}
